package com.cover.fti;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class ScoreDatabase extends SQLiteOpenHelper {
	private static final String HIGHSCORE_DB_NAME = "Highscores";
	private static final int DATABASE_VERSION = 2;

	public ScoreDatabase(Context context) {
		super(context, HIGHSCORE_DB_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase sql) {
		sql.execSQL("CREATE TABLE score (tanggal TEXT, score LONG)");
	}

	@Override
	public void onUpgrade(SQLiteDatabase sql, int arg1, int arg2) {
		sql.execSQL("DROP TABLE IF EXIST score");
		onCreate(sql);
	}

	public Score getHighScore(Context context) {
		Score highscore = new Score();
		ScoreDatabase db = new ScoreDatabase(context);
		SQLiteDatabase data = db.getReadableDatabase();
		Cursor c = data.query("score", new String[] { "tanggal", "score" },
				null, null, null, null, null);
		while (c.moveToNext()) {
			highscore.setTanggal(c.getString(0));
			highscore.setHighScores(c.getLong(1));
		}
		c.close();
		data.close();
		return highscore;
	}

	public void insertNewScore(Context context, Score sc) {
		ScoreDatabase db = new ScoreDatabase(context);
		SQLiteDatabase data = db.getReadableDatabase();
		ContentValues cv = new ContentValues();
		cv.put("tanggal", sc.getTanggal());
		cv.put("score", sc.getHighScores());
		data.insert("score", null, cv);
		data.close();
	}

	public void updateScore(Context context, String tglLama,
			String tglBaru, long scoreBaru) {
		ScoreDatabase db = new ScoreDatabase(context);
		SQLiteDatabase data = db.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put("tanggal", tglBaru);
		cv.put("score", scoreBaru);
		data.update("score", cv, "tanggal = '" + tglLama + "'", null);
		data.close();
	}
}
